<?php

namespace App\Http\Controllers;

use App\Models\User;

use Auth;
use JWTAuth;
use Validator;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Http\Requests;

class AccountController extends Controller
{
  public function index()
  {
    $users = User::all();
    return $this->success(0, '', $users);
  }

  public function login(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'name' => 'between:4,32|alpha_dash|exists:users',
      'password' => 'required|between:6,32',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $credentials = $request->only('name', 'password');
    try {
      if (!$token = JWTAuth::attempt($credentials)) {
        return $this->failure(-1, trans('auth.failed'));
      }
      return $this->success(0, '', ['token' => $token]);
    } catch (JWTException $e) {
      return $this->failure(-1, trans('jwt.could_not_create_token'));
    }
  }

  public function logout(Request $request)
  {
    try {
      JWTAuth::parseToken()->invalidate();
    } catch (TokenBlacklistedException $e) {
      return $this->failure(-1, trans('jwt.the_token_has_been_blacklisted'));
    } catch (JWTException $e) {
      // 忽略该异常（Authorization为空时会发生）
    }
    return $this->success();
  }

  public function getUserInfo(Request $request)
  {
    $user = JWTAuth::parseToken()->authenticate();
    if($user->id == 1) {
      $user->role = ['admin'];
    }
    return $this->success(0,'', $user);
  }

  public function settings()
  {
    $user = User::first();
    if ($user) {
        $data = [
            'sex_limited' => $user->sex_limited,
            'delay_time' => $user->delay_time,
            'maxed_wechat_request_num' => $user->maxed_wechat_request_num,
            'maxed_qq_request_num' => $user->maxed_qq_request_num,
            'phone_get_num' => $user->phone_get_num,
            'maxed_wechat_search_num' => $user->maxed_wechat_search_num,
            'search_time' => $user->search_time,
            'add_time' => $user->add_time,
            'add_per_num' => $user->add_per_num,
            'cycle_delay' => $user->cycle_delay,
            'daily_card_num' => $user->daily_card_num,
            'article_wechat' => $user->article_wechat,
            'write_data' => ($user->write_data == 1) ? true : false
        ];
        $zfb_filter = explode(':',$user->zfb_filter);
        $data['zfb_filter'] = $zfb_filter[0] == 1 ? $zfb_filter[1] : false;
        $card_time = explode(':',$user->card_time);
        $data['card_time'] = $card_time[0] == 1 ? $card_time[1] : false;
        $article_time = explode(':',$user->article_time);
        $data['article_time'] = $article_time[0] == 1 ? $article_time[1] : false;
        $random_action = explode(':',$user->random_action);
        $data['random_action'] = $random_action[0] == 1 ? $random_action[1] : false;
        $applet = explode(':',$user->applet);
        $data['applet'] = $applet[0] == 1 ? $applet[1] : false;
        $foster = explode(':',$user->foster);
        $data['foster'] = $foster[0] == 1 ? $foster[1] : false;
        return $this->success(0, 'OK', $data);
    }
    return $this->failure(-1, 'No data');
  }

  public function updateSettings(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'delay_time' => 'required|numeric',
      'maxed_wechat_request_num' => 'required|numeric',
      'maxed_wechat_search_num' => 'required|numeric',
      'phone_get_num' => 'sometimes|required|numeric',
      'sex_limited' => 'required|numeric',
      'search_time' => 'required|numeric',
      'add_time' => 'required|numeric',
      'add_per_num' => 'required|numeric',
      'cycle_delay' => 'required|numeric',
      'daily_card_num' => 'required|numeric',
//      'article_wechat' => 'required',
//      'card_time' => 'required',
//      'article_time' => 'required',
//      'random_action' => 'required',
//      'applet' => 'required'
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $credentials = $request->only(
        'delay_time', 'maxed_wechat_request_num', 'maxed_wechat_search_num',
        'phone_get_num', 'sex_limited','search_time', 'add_time', 'add_per_num',
        'cycle_delay', 'daily_card_num', 'article_wechat','write_data','zfb_filter',
        'card_time','article_time','random_action', 'applet', 'foster'
    );
    $user = JWTAuth::parseToken()->authenticate();
    if ($user) {
        $user->update($credentials);
        return $this->success(0, '设置成功', $user);
    }
    return $this->failure(-1, '设置失败');
  }

  public function updatePassword(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'oldPass' => 'required|between:6,32',
      'newPass' => 'required|between:6,32',
      'checkNewPass' => 'required|between:6,32|same:newPass',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $credentials = array(
      'id'       => $request->user_id,
      'password' => $request->oldPass,
    );
    if (!Auth::attempt($credentials, true)) {
      return $this->failure(-1,'原密码错误。');
    }
    $credential = $request->only('oldPass', 'newPass', 'checkNewPass');
    $user = User::find($request->user_id);
    if ($user) {
      $user->password = bcrypt($credential['newPass']);
      $user->save();
      return $this->success(0, '更新成功', $user);
    }
    return $this->failure(-1, '没有找到对应的用户');
  }
}
